package com.echoesnet.echoesshortvideo.Activities;


import android.Manifest;
import android.app.Dialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.echoesnet.echoesshortvideo.Beans.IncludeNavBarBean;
import com.echoesnet.echoesshortvideo.Beans.PublishVideoBean;
import com.echoesnet.echoesshortvideo.Constant.CommonConstant;
import com.echoesnet.echoesshortvideo.Constant.EsvConstant;
import com.echoesnet.echoesshortvideo.Fragments.HomePageFollowListFragment;
import com.echoesnet.echoesshortvideo.Fragments.HomePageVideoListFragment;
import com.echoesnet.echoesshortvideo.Fragments.SecondLayerFragment;
import com.echoesnet.echoesshortvideo.Fragments.UserDetailFragment;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.CrashHandler;
import com.echoesnet.echoesshortvideo.Utils.NetUtil;
import com.echoesnet.echoesshortvideo.Utils.NetUtilListener;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.View.BottomSelector;
import com.echoesnet.echoesshortvideo.ViewModels.MainModel;
import com.echoesnet.echoesshortvideo.ViewModels.SettingViewModel;
import com.echoesnet.echoesshortvideo.databinding.ActMainBinding;
import com.echoesnet.echoesshortvideo.views.dialog.CustomAlertDialog;
import com.echoesnet.echoesshortvideo.views.dialog.DialogWith2BtnAtBottom;
import com.echoesnet.echoesshortvideo.views.dialog.DownloadAlertDialog;
import com.orhanobut.logger.Logger;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainAct extends BaseActivity
{
    private static final String TAG = MainAct.class.getSimpleName();
    public static final String INTENT_STRING_TABNAME = "intent_String_tabname";
    public static final String INTENT_INT_INDEX = "intent_int_index";

    private static final int STATUS_UPLOADING = 0x001;//上传中
    private static final int STATUS_PUBLISH_SUCCESS = 0x002;//上传成功
    private static final int STATUS_PUBLISH_FAIL = 0x003;//上传失败


    @BindView(R.id.takeVideo)
    ImageView takeVideo;
    @BindView(R.id.ll_publish_video_progress)
    LinearLayout llPublishVideoProgress;
    @BindView(R.id.pb_publish_video)
    ProgressBar pbPublishVideo;
    @BindView(R.id.tv_publish_video_progress)
    TextView tvPublishVideoProgress;


    private IndicatorViewPager indicatorViewPager;
    private LayoutInflater inflate;
    private MainModel mainModel;
    private MainAct mAct;
    private BottomSelector bottomSelector;
    private PublishVideoReceiver publishVideoReceiver;
    private UserDetailFragment userFrag;
    private String[] tabNames = {"首页", "关注", "消息", "我的"};
    private boolean isShowMain = false;
    private int publishStatus = -1; //发布状态
    private HomePageVideoListFragment homeFrag;
    private CustomAlertDialog customAlertDialog;
    private SettingViewModel setViewModel;

    public static final String SELECT_PAGE_INDEX="SELECT_PAGE_INDEX" ;


    private ActMainBinding actBinding;
    private IncludeNavBarBean navBean;
    @Override
    protected void onCreate(Bundle arg0)
    {
        super.onCreate(arg0);
        //add 3s welcome activity
//        WelcomeAct.start(this,2);
        actBinding = DataBindingUtil.setContentView(this, R.layout.act_main);
//        setContentView(R.layout.act_main);   --> 注意这里不需要了 这里是样例； databing采用上面的方法
        navBean = new IncludeNavBarBean(true, false);
        actBinding.relNavBar.setNavBean(navBean);


        ButterKnife.bind(this);
        Resources res = getResources();
        mAct = this;
        mainModel = new MainModel();
        setViewModel = ViewModelProviders.of(this).get(SettingViewModel.class);
        publishVideoReceiver = new PublishVideoReceiver();

        ViewPager viewPager = (ViewPager) findViewById(R.id.vpTabMain);
        Indicator indicator = (Indicator) findViewById(R.id.fivTabs);
        ColorBar colorBar = new ColorBar(getApplicationContext(), Color.WHITE, 4);
        colorBar.setWidth(100);
        indicator.setScrollBar(colorBar);

        float unSelectSize = 18;
//        float selectSize = unSelectSize * 1.2f;
        float selectSize = unSelectSize;
        int selectColor = res.getColor(R.color.white);
        int unSelectColor = res.getColor(R.color.whiteT50);
        indicator.setOnTransitionListener(new OnTransitionTextListener().setColor(selectColor, unSelectColor).setSize(selectSize, unSelectSize));

        indicator.setOnIndicatorItemClickListener(new Indicator.OnIndicatorItemClickListener()
        {
            @Override
            public boolean onItemClick(View clickItemView, int position)
            {
                if (TextUtils.isEmpty(SharePreUtils.getUId()) || TextUtils.isEmpty(SharePreUtils.getToken()))
                {
                    if (position != 0)
                    {
                        return !CommonUtils.checkUserStateFromActivity(mAct, null);
                    }
                }
                return false;
            }
        });

        viewPager.setOffscreenPageLimit(4);
        indicatorViewPager = new IndicatorViewPager(indicator, viewPager);
        inflate = LayoutInflater.from(getApplicationContext());
        indicatorViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
        indicatorViewPager.setOnIndicatorPageChangeListener((preItem, currentItem) -> {
            if (TextUtils.isEmpty(SharePreUtils.getUId()) || TextUtils.isEmpty(SharePreUtils.getToken()))
            {
                if (!(currentItem == 0))
                {
                    CommonUtils.checkUserStateFromActivity(mAct, null);
                    indicatorViewPager.setCurrentItem(0, false);
                }
            }
        });
        pbPublishVideo.setMax(100);
        initPopWindow();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(EsvConstant.ACTION_NOTIFY_PUBLISH_VIDEO);
        intentFilter.addAction(CommonConstant.REQUEST_LOGIN_CODE);
        LocalBroadcastManager.getInstance(mAct).registerReceiver(publishVideoReceiver, intentFilter);
        takeVideo.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                if (publishStatus != STATUS_UPLOADING)
                {
                    if (CommonUtils.checkUserStateFromActivity(mAct,null))
                    {
                        NetUtil.checkIsBindMobile(new NetUtilListener()
                        {
                            @Override
                            public void onSuccess()
                            {
                                bottomSelector.show(takeVideo);
                            }

                            @Override
                            public void onFail()
                            {
                                new CustomAlertDialog(mAct).builder()
                                        .setMsg("\n发视频需要绑定手机号,是否去绑定手机")
                                        .setCancelable(false)
                                        .setNegativeTextColor(ContextCompat.getColor(mAct, R.color.C0322))
                                        .setPositiveTextColor(ContextCompat.getColor(mAct, R.color.C0321))
                                        .setPositiveButton("去绑定", view1 -> {
                                            Intent intent = new Intent(mAct, BindPhoneAct.class);
                                            startActivity(intent);
                                        })
                                        .setNegativeButton("暂不绑定",null).show();
                            }
                        });
                    }
                }
                else
                {
                    ToastUtils.showShort( "视频上传中....");
                }
            }
        });
        StatService.start(this);


        //--测试代码 可删除--------↓--------------------
//        findViewById(R.id.login).setOnClickListener(new View.OnClickListener()
//        {
//            @Override
//            public void onClick(View v)
//            {
//                CommonUtils.startLoginFromActivity(MainAct.this,null);
//            }
//        });
        //--测试代码 可删除--------↑--------------------

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            MainActPermissionsDispatcher.onSDCardPermGrantedWithPermissionCheck(mAct);
        }
        else
        {
            onSDCardPermGranted();
        }

        setViewModel.getVersionInfoBack().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String str)
            {
                //检查强更或者不强更安装包
                try
                {
                    JSONObject obj = new JSONObject(str);
                    String ServerVersion = obj.getString("version");
                    int SerVersion = Integer.parseInt(ServerVersion);
                    final String url = obj.getString("url");
                    final String type = obj.getString("type");
                    final String updateContent = obj.getString("desc");
                    Logger.t(TAG).d("SerVersion:" + SerVersion + ",versionCode" + CommonUtils.getVerCode(mAct));
                    if (CommonUtils.getVerCode(mAct) < SerVersion)
                    {
                        View view = LayoutInflater.from(mAct).inflate(R.layout.dialog_download_apk, null);
                        TextView tvContent = (TextView) view.findViewById(R.id.update_content);
                        tvContent.setText(updateContent);
                        if (type.equals("1"))//强制更新
                        {
                            new CustomAlertDialog(mAct)
                                    .builder()
                                    .setMsg(updateContent)
                                    .setCancelable(false)
                                    .configContentView(Gravity.LEFT | Gravity.CENTER_VERTICAL)
                                    .setPositiveBtnClickListener("体验最新版本", new CustomAlertDialog.OnDialogWithPositiveBtnListener()
                                    {
                                        @Override
                                        public void onPositiveBtnClick(View view, Dialog dialog)
                                        {
                                            int i =NetUtil.getNetworkStatus(mAct);
                                            if (i == -1)
                                            {
                                                ToastUtils.showShort("请检查网络");
                                                finish();
                                            }
                                            else
                                            {
                                                updateApk(url, true);
                                            }
                                        }
                                    }).show();
                        }
                        else
                        {
                            new DialogWith2BtnAtBottom(mAct)
                                    .buildDialog(mAct)
                                    .setDialogTitle("发现新版本，现在就去下载！", false)
                                    .setContent(view)
                                    .setCancelable(false)
                                    .setCommitBtnClickListener(new DialogWith2BtnAtBottom.OnDialogWithPositiveBtnListener()
                                    {
                                        @Override
                                        public void onPositiveBtnClick(View view, Dialog dialog)
                                        {
                                            int i = NetUtil.getNetworkStatus(mAct);
                                            if (i == -1)
                                            {
                                                ToastUtils.showShort("当前无网络连接,更新失败！");
                                                dialog.dismiss();
                                            }
                                            else if (i == 1)
                                            {
                                                ToastUtils.showShort("开始下载...");
//                                                Intent updateIntent = new Intent(MainAct.this, UpdateAPKService.class);
//                                                updateIntent.putExtra("apkName", "小录段子");
//                                                updateIntent.putExtra("apkUrl", url);
//                                                startService(updateIntent);
                                                updateApk(url,false);
                                                dialog.dismiss();
                                            }
                                            else
                                            {
                                                new CustomAlertDialog(mAct)
                                                        .builder()
                                                        .setMsg(getString(R.string.mobie_net_tip))
                                                        .setTitle("提示")
                                                        .setCancelable(false)
                                                        .setPositiveButton("继续更新", new View.OnClickListener()
                                                        {
                                                            @Override
                                                            public void onClick(View v)
                                                            {
                                                                ToastUtils.showShort("开始下载...");
//                                                                Intent updateIntent = new Intent(MainAct.this, UpdateAPKService.class);
//                                                                updateIntent.putExtra("apkName", "小录段子");
//                                                                updateIntent.putExtra("apkUrl", url);
//                                                                startService(updateIntent);
                                                                updateApk(url,false);
                                                                dialog.dismiss();
                                                            }
                                                        }).setNegativeButton("取消", new View.OnClickListener()
                                                {
                                                    @Override
                                                    public void onClick(View view)
                                                    {
                                                        dialog.dismiss();
                                                    }
                                                }).show();
                                            }
                                   //   updateApk(url,false);
                                        }
                                    })
                                    .setCancelBtnClickListener(new DialogWith2BtnAtBottom.OnDialogWithNavigateBtnListener()
                                    {
                                        @Override
                                        public void onNavigateBtnClick(View view, Dialog dialog)
                                        {
                                            int i = NetUtil.getNetworkStatus(mAct);
                                            if (type.equals("1") || i == -1)
                                            {
                                                finish();
                                            }
                                            else
                                            {
                                                dialog.dismiss();
                                            }
                                        }
                                    })
                                    .show();
                        }
                    }
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }

            }
        });

        setViewModel.getVersionUpdate(CommonUtils.getVerCode(this) + "", "1");
    }

    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        if (indicatorViewPager!=null)
        {
            indicatorViewPager.setCurrentItem(getIntent().getIntExtra(SELECT_PAGE_INDEX,0), true);
        }
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if (isShowMain && indicatorViewPager != null)
        {
            isShowMain = false;
            indicatorViewPager.setCurrentItem(0, true);
        }

    }

    private void initPopWindow()
    {
        bottomSelector = new BottomSelector(mAct, Arrays.asList(new String[]{"拍摄", "本地上传"}))
                .setFirstClickListener(new BottomSelector.OnItemClickListener()
                {
                    @Override
                    public void onItemClick(View view, BottomSelector pop)
                    {
                        //拍摄
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                        {
                            MainActPermissionsDispatcher.onCameraAudioPermGrantedWithPermissionCheck(mAct);
                            MainActPermissionsDispatcher.onSDCardPermGrantedWithPermissionCheck(mAct);
                        }
                        else
                        {
                            onCameraAudioPermGranted();
                        }
                    }
                }).setSecondClickListener(new BottomSelector.OnItemClickListener()
                {
                    @Override
                    public void onItemClick(View view, BottomSelector pop)
                    {
                        //本地上传
                        Intent setIntent = new Intent(mAct, VideoSelectAct.class);
                        startActivity(setIntent);
                        pop.dismiss();
                    }
                });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        return super.onTouchEvent(event);
    }

    private class PublishVideoReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (EsvConstant.ACTION_NOTIFY_PUBLISH_VIDEO.equals(intent.getAction()) && !mAct.isFinishing())
            {
                Logger.t(TAG).d("收到广播>>>>>>>>>>>");
                publishStatus = STATUS_UPLOADING;
                if (llPublishVideoProgress.getVisibility() == View.GONE)
                {
                    tvPublishVideoProgress.setText("上传中...");
                    llPublishVideoProgress.setVisibility(View.VISIBLE);
                }
                indicatorViewPager.setCurrentItem(0, false);
                String path = intent.getStringExtra("path");
                String thumbnailPath = intent.getStringExtra("thumbnailPath");
                String showType = intent.getStringExtra("showType");
                String content = intent.getStringExtra("content");
                String location = intent.getStringExtra("location");
                String posx = intent.getStringExtra("posx");
                String posy = intent.getStringExtra("posy");
                PublishVideoBean publishVideoBean = new PublishVideoBean();
                publishVideoBean.setUrl(path);
                publishVideoBean.setThumbnails(thumbnailPath);
                publishVideoBean.setShowType(showType);
                publishVideoBean.setContent(content);
                publishVideoBean.setLocation(location);
                publishVideoBean.setPosx(posx);
                publishVideoBean.setPosy(posy);
                mainModel.publishVideo(publishVideoBean).observe(mAct, publishVideoProgressBean -> {
                    if (publishVideoProgressBean != null)
                    {
                        long progress = publishVideoProgressBean.getProgress();
                        Logger.t(TAG).d(">>>>>>>>>>>>>>>>>>>>>>>" + progress + "|" + publishVideoBean.toString());
                        Logger.t(TAG).d(">>>>>>>>>>>>>>>>>>>>>>>" + publishVideoProgressBean.toString());
                        if (progress >= 0)
                        {
                            Observable.create(new ObservableOnSubscribe<Object>()
                            {
                                @Override
                                public void subscribe(ObservableEmitter<Object> emitter) throws Exception
                                {
                                    Logger.t(TAG).d("thread >>>" + Thread.currentThread().getName());
                                    if (pbPublishVideo.getProgress() != progress)
                                        pbPublishVideo.setProgress((int) progress);
                                    emitter.onNext("0");
                                }
                            }).subscribeOn(Schedulers.single())
                                    .subscribe(new Consumer<Object>()
                                    {
                                        @Override
                                        public void accept(Object o) throws Exception
                                        {

                                        }
                                    });

                        }
                        if ("0".equals(publishVideoProgressBean.getStatus()))
                        {
                            Logger.t(TAG).d(">>>>>>>>>>>>>>>>>>>>>>>" + publishVideoBean.toString());
                            if (homeFrag != null)
                                homeFrag.getViewModel().requestRefresh();
                            publishStatus = STATUS_PUBLISH_SUCCESS;
                            ToastUtils.showShort( "发布成功");
                            tvPublishVideoProgress.setText("上传成功");
                            Intent intent11 = new Intent(EsvConstant.ACTION_NOTIFY_MY_VIDEO_NUM);
                            LocalBroadcastManager.getInstance(MainAct.this).sendBroadcast( intent11);
                            new Handler().postDelayed(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    llPublishVideoProgress.setVisibility(View.GONE);
                                }
                            }, 1000);
                        }
                        if (!TextUtils.isEmpty(publishVideoProgressBean.getCode()))
                        {
                            publishStatus = STATUS_PUBLISH_FAIL;
                            tvPublishVideoProgress.setText("上传失败");
                            new Handler().postDelayed(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    llPublishVideoProgress.setVisibility(View.GONE);
                                }
                            }, 1000);
                        }
                    }
                });
            }
            else if(CommonConstant.REQUEST_LOGIN_CODE.equals(intent.getAction()))
            {
                 isShowMain=true;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == CommonConstant.RESULT_CODE_OK)
        {
            switch (requestCode)
            {
                case CommonConstant.REQUEST_CODE_LOGIN:
                    break;
            }
        }
        else
        {
            switch (requestCode)
            {
                case CommonConstant.REQUEST_CODE_LOGIN:
                    indicatorViewPager.setCurrentItem(0, true);
                    break;
            }
        }
    }

    private class MyAdapter extends IndicatorViewPager.IndicatorFragmentPagerAdapter
    {

        public MyAdapter(FragmentManager fragmentManager)
        {
            super(fragmentManager);
        }

        @Override
        public int getCount()
        {
            return tabNames.length;
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container)
        {
            if (convertView == null)
            {
                convertView = inflate.inflate(R.layout.tab_top, container, false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(tabNames[position]);
            return convertView;
        }

        @Override
        public Fragment getFragmentForPage(int position)
        {
            Logger.t(TAG).d("getFragmentForPage: " + position);
            if (position == 0)
            {
                homeFrag = new HomePageVideoListFragment();
                Bundle bundle = new Bundle();
                bundle.putString(SecondLayerFragment.INTENT_STRING_TABNAME, tabNames[position]);
                bundle.putInt(SecondLayerFragment.INTENT_INT_POSITION, position);
                homeFrag.setArguments(bundle);
                return homeFrag;
            }
            else if (position == 3)
            {
                userFrag = new UserDetailFragment();
                return userFrag;
            }
            else if (position == 1 || position == 2)
            {
                HomePageFollowListFragment followListFragment = new HomePageFollowListFragment();
                return followListFragment;
            }
            SecondLayerFragment mainFragment = new SecondLayerFragment();
            Bundle bundle = new Bundle();
            bundle.putString(SecondLayerFragment.INTENT_STRING_TABNAME, tabNames[position]);
            bundle.putInt(SecondLayerFragment.INTENT_INT_POSITION, position);
            mainFragment.setArguments(bundle);
            return mainFragment;
        }
    }

    @NeedsPermission({android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCameraAudioPermGranted()
    {
        Logger.t(TAG).d("允许获取权限");
        if (CommonUtils.cameraIsCanUse() && CommonUtils.isVoicePermission())
        {
            Intent cameraIntent = new Intent(mAct, CameraAct.class);
            startActivity(cameraIntent);
            if (bottomSelector != null)
                bottomSelector.dismiss();
        }
        else
        {
            if (customAlertDialog == null)
            customAlertDialog = new CustomAlertDialog(mAct)
                    .builder()
                    .setCancelable(false)
                    .configContentView(Gravity.LEFT)
                    .setMsg(mAct.getString(R.string.tips_not_camera))
                    .setCancelBtnClickListener("确定", new CustomAlertDialog.OnDialogWithNavigateBtnListener()
                    {
                        @Override
                        public void onNavigateBtnClick(View view, Dialog dialog)
                        {
                            dialog.dismiss();
                        }
                    });
            customAlertDialog.show();
        }
    }

    @OnPermissionDenied({android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onCameraAudioPermDenied()
    {
        Logger.t(TAG).d("拒绝获取权限");
        ToastUtils.showShort("小饭没有获得相应的权限，无法为您进一步提供服务");
    }

    @OnNeverAskAgain({android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO})
    void onCameraAudioPermNeverAsk()
    {
        Logger.t(TAG).d("点击了不要再次询问获取权限");
        ToastUtils.showShort( getString(R.string.per_camera_never_ask));
    }

    @OnShowRationale({android.Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO})
    void onCameraAudioPermReason(final PermissionRequest request)
    {
        Logger.t(TAG).d("说明");
        new CustomAlertDialog(mAct)
                .builder()
                .setTitle("请求权限说明")
                .setMsg("需要使用您的相机和录音权限才能完成此功能！")
                .setPositiveButton("允许", new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        request.cancel();
                    }
                }).show();
    }


    @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onSDCardPermGranted()
    {
        Logger.t(TAG).d("允许获取权限");
        CrashHandler.getRootDirPath(mAct);
    }

    @OnPermissionDenied({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onSDCardPermDenied()
    {
        Logger.t(TAG).d("拒绝获取权限");
        ToastUtils.showShort("小饭没有获得存储的权限，无法为您进一步提供服务");
    }

    @OnNeverAskAgain({ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onSDCardPermNeverAsk()
    {
        Logger.t(TAG).d("点击了不要再次询问获取权限");
        ToastUtils.showShort( getString(R.string.per_storage_never_ask));
    }

    @OnShowRationale({ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onSDCardPermReason(final PermissionRequest request)
    {
        Logger.t(TAG).d("说明");
        new CustomAlertDialog(mAct)
                .builder()
                .setTitle("请求权限说明")
                .setMsg("需要使用您的本地存储！")
                .setPositiveButton("允许", new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        request.cancel();
                    }
                }).show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MainActPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    protected void onDestroy()
    {
        LocalBroadcastManager.getInstance(mAct).unregisterReceiver(publishVideoReceiver);
        super.onDestroy();
    }
    private void updateApk(String url, boolean isForceUpdate)
    {
        String netStat = "";
        //返回值 -1：没有网络  1：WIFI网络2：wap网络3：net网络
        int i = NetUtil.getNetworkStatus(mAct);
        if (i == -1)
        {
            ToastUtils.showShort("当前无网络连接,更新失败！");
            return;
        }
        switch (i)
        {
            case 1:
                netStat = "WiFi网络";
                //WiFi网络
                showDownloadDialog(url);
                break;
            case 2:
            case 3:
                netStat = "移动网络";
                new CustomAlertDialog(mAct)
                        .builder()
                        .setMsg("当前为移动网络环境，是否进行更新？")
                        .setTitle("提示")
                        .setCancelable(false)
                        .setPositiveButton("继续更新", new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                showDownloadDialog(url);
                            }
                        }).setNegativeButton("退出", new View.OnClickListener()
                {
                    @Override
                    public void onClick(View view)
                    {
                        if (isForceUpdate)
                        {
                            finish();
                        }
                    }
                }).show();
                break;
        }
    }
    private void showDownloadDialog(String url)
    {
        // 弹出下载Dialog
        new DownloadAlertDialog(mAct)
                .build()
                .setTitle("小录段子.apk")
                .setImage(R.mipmap.ic_launcher)
                .setDownLoadFileUrl(url)
                .show();
    }

}